//
//  FUNTLDBHelper.m
//  FuntlFramework
//
//  Created by liweimin on 13-11-13.
//  Copyright (c) 2013年 liweimin. All rights reserved.
//

#import "FUNTLDBHelper.h"

//#define DATABASE_FILE_NAME @"worldpalm.sqlite"
//#define DATABASE_RESOURCES_NAME @"worldpalm"
//#define DATABASE_RESOURCES_TYPE @"sqlite"
//
//const int dbVersion = 8;

@implementation FUNTLDBHelper

//获取数据库文件的路径
+(NSString *)getDatabasePath:(NSString *)fileName {
	NSArray *searchPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
	NSString *documentFolderPath = [searchPath objectAtIndex:0];
	NSString *dbFilePath = [documentFolderPath stringByAppendingPathComponent:fileName];
	return dbFilePath;
}

//拷贝数据库文件到Documents目录下
+(BOOL)copyDataSourceToDocuments:(NSString *)fileName resourceName:(NSString *)resourceName resourceType:(NSString *)resourceType dbVersion:(int)dbVersion {
    BOOL flag = YES;
	BOOL isExit = [[NSFileManager defaultManager]fileExistsAtPath:[self getDatabasePath:fileName]];
	if(!isExit) {
	    //NSLog(@"数据库文件不存在");
		NSString *DatabasePath = [[NSBundle mainBundle]pathForResource:resourceName ofType:resourceType];
		if(DatabasePath == nil) {
		    flag = NO;
		}
		else {
		    BOOL isCopy = [[NSFileManager defaultManager]copyItemAtPath:DatabasePath toPath:[self getDatabasePath:fileName] error:nil];
			if(!isCopy) {
			    flag = NO;
			}
		}
	} else if ([[NSUserDefaults standardUserDefaults] integerForKey:@"dbVersion"] < dbVersion) {
        //NSLog(@"数据库文件不存在");
        
		NSString *DatabasePath = [[NSBundle mainBundle]pathForResource:resourceName ofType:resourceType];
        
        //删除原有的数据库
        [[NSFileManager defaultManager] removeItemAtPath:[self getDatabasePath:fileName] error:nil];
        
        if(DatabasePath == nil) {
		    flag = NO;
		}
		else {
		    BOOL isCopy = [[NSFileManager defaultManager]copyItemAtPath:DatabasePath toPath:[self getDatabasePath:fileName] error:nil];
			if(!isCopy) {
			    flag = NO;
			} else {
                [[NSUserDefaults standardUserDefaults] setInteger:dbVersion forKey:@"dbVersion"];
            }
		}
    } else {
	    //NSLog(@"数据库文件已存在");
	}
	return flag;
}

@end
